<template>
  <div class="contain">
    <div class="fileInput">
      <input type="file" id="file" />
    </div>
    <van-button size="large" type="info" class="footerBtn" @click="go('canvas')"
      >查看</van-button
    >
  </div>
</template>
<script>
export default {
  data() {
    return {};
  },
  methods: {
    go(url) {
      this.$router.push({
        path: url,
      });
    },
    uploadExcel() {
      document.getElementById("file").addEventListener("change", function (e) {
        var files = e.target.files;
        var name = [];
        name = files[0].name.split(".")[1];
        if (name != "xlsx") {
          alert("文件类型不正确，仅支持xlsx类型文件（全小写）");
          return;
        }
        var fileReader = new FileReader(); // 将文件内容读入内存
        fileReader.onload = function (ev) {
          // 当读取操作成功完成时调用
          // console.log(this.result); // 查看文件输出内容
          try {
            var data = ev.target.result,
              //以二进制流方式读取得到表格中数据
              workbook = XLSX.read(data, { type: "binary" }),
              info = []; //存储获取到的数据
          } catch (e) {
            alert("文件类型不正确");
            return;
          }
          var fromTo = "";
          //遍历每张表读取
          for (var sheet in workbook.Sheets) {
            if (workbook.Sheets.hasOwnProperty(sheet)) {
              fromTo = workbook.Sheets[sheet]["!ref"];
              info = info.concat(
                XLSX.utils.sheet_to_json(workbook.Sheets[sheet])
              );
            }
            break; //仅第一张表
          }
          localStorage.setItem("cards", JSON.stringify(info));
          console.log(workbook);
        };
        //以二进制方式打开文件
        fileReader.readAsBinaryString(files[0]);
      }),
        false;
    },
  },
  mounted() {
    const oScript = document.createElement("script");
    oScript.type = "text/javascript";
    oScript.src = "https://unpkg.com/xlsx@0.13.3/dist/xlsx.full.min.js";
    document.body.appendChild(oScript);
    this.uploadExcel();
  },
};
</script>
<style scoped lang="less">
.contain {
  position: relative;
  text-align: start;
  height: calc(~"100vh - 56px");
}
.footerBtn {
  position: absolute;
  bottom: 0;
}
.fileInput {
  padding: 50px;
}
</style>
